package com.cskaoyan.mall.filter;

import com.cskaoyan.mall.utils.Result;
import com.google.gson.Gson;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @ClassName: MallFilter
 * @Description: TODO
 * @Auther 庄左
 * @Date 2022/7/3 15:17
 * @Version
 **/
@WebFilter("/api/mall/*")
public class MallFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        // response.setHeader("Access-Control-Allow-Origin", "http://localhost:8085");
        response.setHeader("Access-Control-Allow-Origin", "http://192.168.3.19:8085");
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization,Content-Type");
        response.setHeader("Access-Control-Allow-Credentials", "true");

        // String requestURI = request.getRequestURI();
        // 取session
        // 哪些是需要验证登录，哪些是不需要验证登录？
        String requestURI = request.getRequestURI();
        String uri = requestURI.replace(request.getContextPath() + "/api/mall/", "");
        String method = request.getMethod();
        if (!"OPTIONS".equals(method)) {
                if (uri.contains("order")) {
                    //如果请求的地址不是/api/admin/admin/login那么表示的是需要验证登录状态
                    HttpSession session = request.getSession();
                    String username = (String) session.getAttribute("name");
                    Result result = new Result();
                    result.setMessage("需要登陆才能访问");
                    if (username == null) {
                        //需要登录后才可以访问，但是此时没有登录
                        // response.getWriter().println(new Gson().toJson(result));
                        response.setHeader("refresh", "0.01;url=http://192.168.3.19:8085/");
                        return;
                    }
                }
            }


            filterChain.doFilter(request, response);

        }


        @Override
        public void destroy () {

        }
    }
